package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {
    @Autowired
    private IdService idService;
    @Autowired
    private MongoTemplate mongoTemplatel;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";
    @Override
    public String saveVideo(Video video) {
        try {
            video.setId(ObjectId.get());
            video.setVid(idService.createId(IdType.VIDEO));
            video.setCreated(System.currentTimeMillis());
            mongoTemplatel.save(video);
            return video.getId().toHexString();
        } catch (Exception e) {
           log.error("小视屏上传失败了video="+video,e);
        }
        return null;
    }

    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        List<Long>vids = new ArrayList<>();
        int recommendcount =1;
        if(StrUtil.isNotEmpty(redisData)){
            List<String> vidList = StrUtil.split(redisData, ',');
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0];
            int endIndex = Math.min(startEnd[1], vidList.size());
            for(int i =startIndex;i<endIndex;i++){
             vids.add(Convert.toLong(vidList.get(i)));
            }
           recommendcount=vidList.size();
        }
         if(CollUtil.isEmpty(vids)){
             int totalpage = PageUtil.totalPage(recommendcount,pageSize);
             PageRequest pageRequest = PageRequest.of(page-totalpage-1,pageSize, Sort.by(Sort.Order.desc("created")));
             Query query = new Query().with(pageRequest);
             List<Video> videos = mongoTemplatel.find(query, Video.class);
             pageInfo.setRecords(videos);
             return pageInfo;
         }
         Query query = Query.query(Criteria.where("vid").in(vids));
        List<Video> videos = mongoTemplatel.find(query, Video.class);
        pageInfo.setRecords(videos);
        return pageInfo;
    }

    @Override
    public Video queryVideoById(String publishId) {
       return mongoTemplatel.findById(publishId,Video.class);
    }

    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if(!ObjectUtil.isAllNotEmpty(userId,followUserId)){
            return false;
        }
        try {
            if(isFollowUser(userId,followUserId)){
                return false;
            }
            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());
            mongoTemplatel.save(followUser);
            String rediskey =getVideoFollowUserKey(userId);
            String haskey =String.valueOf(followUserId);
            redisTemplate.opsForHash().put(rediskey,haskey,"1");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private String getVideoFollowUserKey(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }

    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }

        if (!this.isFollowUser(userId, followUserId)) {
            return false;
        }

        //取消关注，删除关注数据即可
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId)
        );
        DeleteResult result = this.mongoTemplatel.remove(query, FollowUser.class);


        if (result.getDeletedCount() > 0) {
            // 同时删除redis中的数据
            String redisKey = this.getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().delete(redisKey, hashKey);
            return true;
        }

        return false;
    }

    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String rediskey =getVideoFollowUserKey(userId);
        String haskey =String.valueOf(followUserId);
        return redisTemplate.opsForHash().hasKey(rediskey,haskey);
    }
}
